<%@page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@include file="/jsp/comm_css_include.jsp"%>
<!-- jqgrid-->
<link
	href="${basePath}/css/plugins/jqgriddemo/css/ui.jqgrid-bootstrap.min.css"
	rel="stylesheet" />
<!doctype html>
<html>
<head>
<style type="text/css">
.ibox-content {
	border: none;
}

.tche-padding {
	padding: 0px 0 15px 15px;
}
</style>
</head>
<body class="gray-bg">
	<div class="container creditbody">
		<div class="iboxtitle">
			<span><i class="glyphicon glyphicon-map-marker"></i>&nbsp;财务相关>收支管理</span>
		</div>
		<div class="buttonfixed">
			<button type="button" class="btn dpbtn_blue" id="save">保存</button>
			<button type="button" class="btn dpbtn_green" id="commit">提交</button>
			<button type="button" class="btn dpbtn_red" id="returnList">返回列表</button>
		</div>
		<a name="yingShouXinXi"><div class="business-manwife">应收信息 </div></a>
		<div class="business-padding">
			<c:choose>
				<c:when test="${!empty feeFundItems }">
					<ul class="thead-tableul thead-tableulbb">
						<c:forEach items="${feeFundItems }" var="feeFundItem"
							varStatus="status">
							<c:if test="${status.index % 7 == 0 }">
								<li>
									<table cellpadding="0" cellspacing="0" border="0"
										class="thead-table" style="width: 100%">
										<thead class="thead-a">
											<tr>
												<th class="col-xs-2 col-sm-2 col-md-3 col-lg-2">序号</th>
												<th class="col-xs-8 col-sm-8 col-md-6 col-lg-4">项目</th>
												<th class="col-xs-2 col-sm-2 col-md-3 col-lg-2">应收</th>
											</tr>
										</thead>
										<tbody class="tbody-a">
											</c:if>
											<tr>
												<td>${feeFundItem.key }</td>
												<td>${feeFundItem.name }</td>
												<td id="fee_td_${feeFundItem.key }"><fmt:formatNumber
														type="number" value="${feeFundItem.feeCount }"
														pattern="0.00" maxFractionDigits="2" /></td>
											</tr>
											<c:if test="${status.index % 7 == 6  || status.last}">
										</tbody>
									</table>
								</li>
							</c:if>
						</c:forEach>
					</ul>
				</c:when>
				<c:otherwise>
       			没有收费项目
       		</c:otherwise>
			</c:choose>
		</div>

		<div class="business-manwife">实收信息</div>
		<div class="ibox-content">
			<button class="btn dpbtn_green" type="button"
				onclick="createdRecord();">添加新收支</button>
			<button class="btn dpbtn_red btnaplly" type="button"
				onclick="delRecord();">删除选中</button>
		</div>
		<div class="business-padding">
			<div class="jqGrid_wrapper">
				<table id="table_list_1"></table>
			</div>
		</div>
		<form class="form-horizontal business-form" id="commentFormsz">
			<div class="business-manwife">收支信息</div>
			<div class="tche-padding">
				<table cellpadding="0" cellspacing="0" border="0"
					class="buyinfor-table">
					<input id="busiId" name="busiId" type="hidden"
						value="${ywBusinessDetail.id }" />
					<input id="customerId" name="customerId" type="hidden"
						value="${ywBusinessDetail.customerId }" />
					<input id="incomeExpensesId" name="incomeExpensesId" type="hidden"
						value="${cwIncomeExpenses.id }" />
					<tr>
						<td align="right"><label class="control-label np">应收款齐全时间：</label>
						</td>
						<td><input id="dateComplete" name="dateComplete"
							required="required" placeholder="时间(必填)"
							class="laydate-icon form-control"
							value="<fmt:formatDate value='${cwIncomeExpenses.dateComplete }' pattern='yyyy-MM-dd'/>" />
						</td>
					</tr>
				</table>
				<table cellpadding="0" cellspacing="0" border="0"
					class="buyinfor-table">
					<tr>
						<td align="right" valign="top"><label
							class="control-label np">应收款备注信息：</label></td>
						<td><textarea class="form-control" style="resize: none;"
								id="income_remarks" name="income_remarks" cols="70" rows="3">${cwIncomeExpenses.remarks }</textarea>
						</td>
					</tr>
				</table>
			</div>
		</form>
		<div class="layer-padding" id="addrecord">
			<table cellpadding="0" cellspacing="0" border="0"
				class="thead-tablec marginsfive">
				<thead>
					<tr>
						<th>代码</th>
						<th>收费项</th>
					</tr>
				</thead>
				<tbody id="tbodyselect">
					<c:forEach items="${fundItems }" var="fundItem">
						<tr>
							<td>${fundItem.key }</td>
							<td>${fundItem.value }</td>
						</tr>
					</c:forEach>
				</tbody>
			</table>
			<div class="div-fixed">
				<table cellpadding="0" cellspacing="0" border="0" width="100%"
					style="bottom: 0px; margin-bottom: 0px;">
					<tr>
						<td width="100%" align="center">
							<div class="ibox-content">
								<button class="btn dpbtn_green" type="button"
									onclick="oksave();">确定</button>
								<button class="btn dpbtn_red" type="button"
									onclick="nocancel();">取消</button>
							</div>
						</td>
					</tr>
				</table>
			</div>
		</div>
		<form class="form-horizontal business-form" id="commentForm">
			<div class="layer-padding" id="recorddj">
				<table cellpadding="0" cellspacing="0" border="0"
					class="buyinfor-table">
					<tr>
						<td align="right"><label class="control-label np">入账日期：</label>
						</td>
						<td><input id="dateItem" name="dateItem" placeholder="入账日期(必填)"
							required="required" class="laydate-icon form-control"
							onclick="laydate({max:laydate.now()});"/></td>
						<td align="right"><label class="control-label np">收入/支出：</label>
						</td>
						<td><mytag:selectTag id="itemdirection" name="itemdirection"
								map="${itemdirection }" others="class='select-control' required='required'" /></td>
					</tr>
					<tr>
						<td align="right"><label class="control-label np">金额：</label>
						</td>
						<td><input class="form-control" type="text" id="amountItem"
							name="amountItem" required="required" placeholder="金额(必填)" /></td>
						<td align="right"><label class="control-label np">收支方式：</label>
						</td>
						<td><mytag:selectTag id="typeRemit" name="typeRemit"
								map="${settlementTypes }" others="class='select-control' required='required'" /></td>
					</tr>
					<!-- <tr>
					<td align="right">
						<label class="control-label np">收支银行：</label>
					</td>
					<td>
						<input class="form-control" type="text" id="bankItem" name="bankItem" required="required" />
					</td>
					<td align="right">
						<label class="control-label np">收支账号：</label>
					</td>
					<td> 
						<input class="form-control" type="text" id="cardnoItem" name="cardnoItem" required="required" />
					</td>	
				</tr>	 -->
					<tr>
						<td align="right"><label class="control-label np">收支账号：</label>
						</td>
						<td colspan="3"><mytag:selectTag id="cardnoItem"
								name="cardnoItem" map="${fundAccount }"
								others="class='select-control'" /></td>
					</tr>
					<tr>
						<td align="right" valign="top"><label class="control-label np">收支明细备注：</label>
						</td>
						<td colspan="3"><textarea class="form-control" cols="5"
							id="income_detail_remarks" name="income_detail_remarks"></textarea></td>
					</tr>
				</table>
				<div class="padding-nono">
				<table cellpadding="0" cellspacing="0" border="0" width="100%">
					<tr>
						<td width="100%" align="center">
							<div class="ibox-content">
								<button class="btn dpbtn_green" type="button"
									onclick="recordsave();">确定</button>
								<button class="btn dpbtn_red" type="button"
									onclick="recordreturn();">返回重选</button>
							</div>
						</td>
					</tr>
				</table>
				</div>
			</div>
		</form>
	</div>

	<!-- public quote -->
	<%@include file="/jsp/comm_js_include.jsp"%>


	<!-- custom js -->
	<%@include
		file="/js/common-dpqc/dpqc-validate/comm_validate_include.jsp"%>

	<!-- jqGrid -->
	<script type="text/javascript" charset="utf-8"
		src="${basePath}/js/plugins/jqgriddemo/js/jquery.jqGrid.min.js"></script>
	<script type="text/javascript" charset="utf-8"
		src="${basePath}/js/plugins/jqgriddemo/js/grid.locale-cn.min.js"></script>

	<!-- layerDate plugin javascript -->
	<script type="text/javascript"
		src="${basePath}/js/plugins/layer/laydate/laydate.js"></script>
	<!--
    	作者：zhangpp
    	时间：2017-04-06
    	描述：js
    -->
	<script type="text/javascript">
  //弹窗以及验证
	var index;
	var indexb;
	var confirmLayer;
	var html;
	var itemCode;
	var itemCodeDisplay;
    $(function(){
    	//外部js调用
	    laydate({
	        elem: '#dateComplete', 
	        event: 'focus',
	        istime: false,
	        format: 'YYYY-MM-DD'
	    });
    	
	    $("#commentFormsz").validate({
            //重写showErrors
            showErrors: function (errorMap, errorList) {
                $.each(errorList, function (i, v) {
                    layer.tips(v.message, v.element, { time: 1500 });
                    return false;
                });  
            },
            /* 失去焦点时验证 */
            onfocusout: function(element) { $(element).valid(); },
            /*  键盘抬起不验证 */
            onkeyup:false,
        }); 
    	
    	$("#commentForm").validate({
            rules: {
            	amountItem:{
            		 allMoney:true,
            	}/* ,
            	cardnoItem:{
            		bankNum:true,
            	} */
            },
            messages: {
            	amountItem:{
            		 allMoney:"金额错误",
            	}/* ,
            	cardnoItem:{
            		bankNum:"卡号错误",
           		} */
            },
            //重写showErrors
            showErrors: function (errorMap, errorList) {
                $.each(errorList, function (i, v) {
                    layer.tips(v.message, v.element, { time: 1500 });
                    return false;
                });  
            },
            /* 失去焦点时验证 */
            onfocusout: function(element) { $(element).valid(); },
            /*  键盘抬起不验证 */
            onkeyup:false,
        }); 
    	
    	$("#tbodyselect tr").click(function(){
    		$(this).addClass("trbgcolor").siblings().removeClass("trbgcolor");
    		itemCode = $(this).children("td").eq(0).text().trim();
    		itemCodeDisplay = $(this).children("td").eq(1).text().trim();
    	});
    	$('#save').click(function(){
    		save();
    	});
    	$('#commit').click(function(){
    		 var validstatus = $("#commentFormsz").valid();
    	   	 if(validstatus) {
    			commit();
    		}else{
    			layer.msg("应收款齐全时间没填，请检查！", {icon: 5});
    		}
    	});
    	$('#returnList').click(function(){
    		window.location.href="${basePath}/web/system/cw/incomeExpenses.jsp";
    	});
    	getData();
    });
	
    
    //提交收支
	function commit(){
    	var tds = $('td[id^="fee_td_"]');
    	var incomeExpensesItems = $("#table_list_1").jqGrid("getRowData");
    	if(tds && tds.length > 0) {
    		var equal = true;
    		for(var i = 0; i < tds.length; i++) {
    			var td = tds[i];
    			var tdId = $(td).attr('id');
    			if(tdId && tdId != '') {
    				var fundCode = tdId.substring('fee_td_'.length, tdId.length);
    				var remitAmount = getTotalFromItems(incomeExpensesItems, fundCode);
    				var tdText = $(td).text();
    				var feeAmount = ((tdText && tdText != '') ? parseFloat(tdText) : 0).toFixed(2);
    				if(feeAmount != remitAmount) {
    					equal = false;
    					confirmLayer = layer.confirm('当前客户应收≠实收，是否确认提交?', {
  						  btn: ['强制提交','暂不提交'] //按钮
  						},function(){
  							save(commitAction);
  							layer.close(confirmLayer);
  						});	
   						return;
    				}
    			} else {
    				//不考虑的异常
    			}
    		}
    		if(equal) {
    			save(commitAction);
    		}
    	} else {
    		if(incomeExpensesItems && incomeExpensesItems.length > 0) {
    			layer.msg("应收项目为空，不允许有收支条目！", {icon: 5,time:1500});
        		return;
    		}
    	}
    	
    	//统计收支项目和
    	function getTotalFromItems(incomeExpensesItems, fundCode){
    		var count = 0;
    		if(fundCode && fundCode != '' && incomeExpensesItems && incomeExpensesItems.length > 0) {
    			for(var j = 0; j < incomeExpensesItems.length; j++) {
    				var incomeExpensesItem = incomeExpensesItems[j];
    				if(fundCode == incomeExpensesItem.itemCode) {
    					count += (incomeExpensesItem.amountItem && incomeExpensesItem.amountItem != '') ? parseFloat(incomeExpensesItem.amountItem) : 0;
    				}
    			}
    		}
    		return count.toFixed(2);
    	}
	}
    
    function commitAction(){
    	$.dpAjax({
    		url:'${basePath}/CwIncomeExpensesController/commit',
    		data:{id:$('#incomeExpensesId').val(),busiId:$('#busiId').val()},
 			success: function(datas){
				layer.msg("提交收支明细成功！", {icon: 6,time:1000});
				setTimeout(function () {
					window.location.href="${basePath}/web/system/cw/incomeExpenses.jsp";
		 		}, 1500);
             }
	    });
    }
    
    //保存收支
    function save(callback){
    	var data = {};
    	data.id = $('#incomeExpensesId').val();
		data.busiId = $('#busiId').val();
		data.cusId = $('#customerId').val();
    	data.dateComplete = $('#dateComplete').val();
    	data.remarks = $('#income_remarks').val();
    	data.details = $("#table_list_1").jqGrid("getRowData");
    	$.dpAjax({
    		url:'${basePath}/CwIncomeExpensesController/incomeExpenses',
    		data:data,
 			success: function(datas){
   				 	$('#incomeExpensesId').val(datas.result);
   					layer.msg("收支明细保存成功！", {icon: 6,time:3000});
   					var ids = $("#table_list_1").jqGrid('getDataIDs');
   					if(ids && ids.length > 0) {
     					for(var i = 0; i < ids.length; i++) {
     						var id = ids[i];
     						if(id && id != ''){
	     						if(id.startWith('replaceId')) {
	     							var oldId = id;
	     							id = id.substring('replaceId'.length, id.length);
	     							$("#table_list_1").jqGrid('setCell',oldId,'replaceId',id);
	     							var newId = $("#table_list_1").jqGrid('getCell',id,'replaceId');
	     						}
     						}
   						}
   					}
   					if(callback) {
   						callback();
   					}
             }
	    });
    }
    var createdRecord = function(){
    	index = layer.open({
			  title:'添加新收支项目',
			  type: 1,
			  area: ['400px', '550px'], //宽高
			  content: $('#addrecord')
		});
    }
    var nocancel = function(){
    	layer.close(index);
    }
    
    var  oksave = function(){
    	if (itemCode && itemCode != ""){
    		indexb = layer.open({
	  			  title:itemCodeDisplay+'登记',
	  			  type: 1,
	  			  area: ['550px', '380px'], //宽高
	  			  content: $('#recorddj')
	  		})
    	} else {
    		layer.msg('收费项进行登记', {icon: 5});
    	}
    	
    }
    
    var recordreturn = function(){
    	clearForm();
    	layer.close(indexb);
    }
	
    var recordsave = function(){
    	 var validstatus = $("#commentForm").valid();
	   	 if(validstatus) {
	    	var dateItem = $('#dateItem').val();
	    	var itemdirection = $('#itemdirection').val();
	    	var itemDirectionDisplay = '';
	    	if(itemdirection && itemdirection != '') {
	    		itemDirectionDisplay = $('#itemdirection option:selected').text().trim();
	    	}
	    	var amountItem = parseFloat($('#amountItem').val()?$('#amountItem').val():'0');
	    	var typeRemit = $('#typeRemit').val();
	    	var typeRemitDisplay = '';
	    	if(typeRemit && typeRemit != '') {
	    		typeRemitDisplay = $('#typeRemit option:selected').text().trim();
	    	}
	    	/* var bankItem = $('#bankItem').val(); */
	    	var cardnoItemValue = $('#cardnoItem').val();
	    	var cardnoItem = '';
	    	if(cardnoItemValue && cardnoItemValue != '') {
	    		cardnoItem = $('#cardnoItem option:selected').text().trim();
	    	}
	    	var remarks = $('#income_detail_remarks').val();
	    	var rowid = 'replaceId' + guid();
	    	$("#table_list_1").jqGrid("addRowData",rowid,
	    			{
	    				replaceId:rowid, 
	    				dateItem:dateItem,
	    				itemCode:itemCode,
	    				itemCodeDisplay:itemCodeDisplay,
	    				itemDirection:itemdirection,
	    				itemDirectionDisplay:itemDirectionDisplay,
	    				amountItem:amountItem,
	    				typeRemit:typeRemit,
	    				typeRemitDisplay:typeRemitDisplay,
	    				/* bankItem:bankItem, */
	    				cardnoItem:cardnoItem,
	    				remarks:remarks
	    			});
	    	save();
	    	clearForm();
	    	layer.closeAll();
	   	 }	
    }
    
   function clearForm(){
    	$('#dateItem').val('');
    	$('#itemdirection').val('');
    	$('#amountItem').val('');
	   	$('#typeRemit').val('');
	   	/* $('#bankItem').val(''); */
	   	$('#cardnoItem').val('');
	   	$('#income_detail_remarks').val('');
    }
   
    function guid() {
   	  function S4() {
   	    return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
   	  }
   	  return S4()+S4()+S4()+S4()+S4()+S4()+S4()+S4();
   	}
   
    var getData = function(){
    	var winWidth = $(window).width();
     	var win = winWidth / 8;
	 	$.jgrid.defaults.styleUI = 'Bootstrap';
	 	   
		  jQuery("#table_list_1").jqGrid({
			postData :{busiId:$('#busiId').val(), cusId:$('#customerId').val()},
			url:'${basePath}/CwIncomeExpensesItemController/list',
	        datatype : "json",
	   //     colNames : ['主键', '入账日期', '费用项目码', '费用项目', '收入/支出码', '收入/支出', '金额','收支方式码','收支方式', '收支银行','收支账号',  '备注'],
	        colNames : ['主键', '入账日期', '费用项目码', '费用项目', '收入/支出码', '收入/支出', '金额','收支方式码','收支方式','收支账号',  '备注'],
	        colModel : [ 
	                     {name: 'replaceId', index: 'id', hidden:true},
	            		 {name: 'dateItem',index: 'dateItem',width: win,align: "center", formatter:function(a) {
	                    	 return formateToDate(a);
	                     }},
	                     {name: 'itemCode',index: 'itemCode',hidden:true},
	            		 {name: 'itemCodeDisplay',index: 'itemCode',width: win,align: "center"},
	            		 {name: 'itemDirection',index: 'itemDirection',hidden:true},
	                  	 {name: 'itemDirectionDisplay',index: 'itemDirection',width: win,align: "center"},
	               		 {name: 'amountItem',index: 'amountItem',width: win,align: "center"},
	               		 {name: 'typeRemit',index: 'typeRemit',hidden:true},
	               		 {name: 'typeRemitDisplay',index: 'typeRemit',width: win,align: "center"},
	            		/*  {name: 'bankItem',index: 'bankItem',width: win,align: "center"}, */
	            		 {name: 'cardnoItem',index: 'cardnoItem',width: win,align: "center"},
	            		 {name: 'remarks',index: 'remarks',width: win,align: "center"}
	                   ],
	          mtype : "post",
	          height: 400,
	          autowidth: false,
	          width:winWidth,  
	          shrinkToFit: false,
	          viewrecords: true,
	          hidegrid: false,
	          multiselect : true,
	          altRows:true,
              altclass:'someClass',
	          jsonReader : {
	        	  root:"result.rows",
	        	  page: "result.page",
	        	  total: "result.total",
	        	  records: "result.records",
	        	  repeatitems: false,
	        	  id: "replaceId"
	          },
	          loadComplete:function(datas){
	        	  if (datas.flag == "100100") {
	                  layer.msg("查询成功!", {icon: 6, time: 1000});
	                  return;
	              }
	        	  if(datas.flag == '100802') {
					  top.location.href = thisLoginUrl;
					  return;
				  }

	        	  layer.msg(datas.message, {icon: 2});
	          }
	      });
    }
  
  	//删除选中
  	function delRecord(){
 	    var ids = $('#table_list_1').jqGrid('getGridParam','selarrrow');
 	    
 	    var temPids = ids.slice();
 	    if(!temPids || temPids.length == 0){
    		layer.msg("请选择要删除的收支明细！", {icon: 5});
    		return;
    	}
 	    
  		for(var i = 0; i < temPids.length; i++){
  			$("#table_list_1").jqGrid("delRowData", temPids[i]);
  		}
  		save();
  	}
    
    window.onresize = function() {
    	$("#table_list_1").setGridWidth($(window).width()-80);
    }
    
    var refresh = function() {
    	$("#table_list_1").jqGrid("setGridParam", { search: true }).trigger("reloadGrid", []);
    }
</script>
</body>
</html>
